package com.aic.aicdetactor.analysis;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.zip.CRC32;

import android.content.Context;
import android.os.Handler;
import android.util.Log;


import com.aic.aicdetactor.CacheControl;
import com.aic.aicdetactor.CustomListAdapter;
import com.aic.aicdetactor.common.CommonDef;
import com.aic.aicdetactor.common.Constants;
import com.aic.aicdetactor.common.Setting;
import com.aic.aicdetactor.crash.AICApplication;
import com.aic.aicdetactor.service.AICService;
import com.aic.aicdetactor.util.ArrayUtil;
import com.aic.aicdetactor.util.HexUtil;
import com.aic.aicdetactor.util.LogUtil;
import com.aic.aicdetactor.util.SystemUtil;
import com.aic.aicdetactor.util.ToastUtil;
import com.aic.xj.app.util.StringUtil;
import com.aic.xj.data.aicdataanalysis.DataAnalysis;
import com.aic.xj.data.aicdataanalysis.FreDomainPara;
import com.aicmonitor.aicdetactorsimple.R;

/**
 * 瑙ｆ瀽鎺ュ彈鍒扮殑BLE鏁版嵁 鐢ㄦ硶濡備笅 ReceivedDataAnalysis analysis = new
 * ReceivedDataAnalysis(); analysis.getDataFromBLE(byte[]data,boolean
 * bStartReceiveData); 濡傛灉鎺ュ彈瀹屾瘯 鎺ョ潃鍒嗘瀽鏁版嵁 boolean isValid =
 * analysis.isValidate();
 * 
 * @author AIC
 *
 */
public class ReceivedDataAnalysis {
	private DataAnalysis _dataAnalysis=new DataAnalysis();//2017-03-03 liuhg添加
	private CubicSpline  m_CubicSpline=new CubicSpline();//2016-03-24 liuhg添加
	
	float[] mReceiveWaveFloatData = null;
	// byte []mReceiveWaveByteData=null;

	byte[] mReceiveBytes = null;
	/**
	 * 鏁版嵁鍖呮暟
	 */
	int mReceivedPackageCounts = 0;
	int caiyangdian = 0;
	int caiyangPinLv = 0;
	int mAxCounts = 0;
	byte mDLCmd = 0;

	final String TAG = "ReceivedDataAnalysis";
	/**
	 * 宸茬粡鎺ユ敹鍒扮殑鏁版嵁闀垮害
	 */
	int mReceivedDataByteSizes = 0;
	/**
	 * 搴旇鑾峰彇鐨勬暟鎹暱搴�
	 */
	int mShoudReceivedByteSizes = 0;
	/**
	 * 鑾峰彇wave鏁版嵁
	 */

	private float mDefaultA = 101.5f;
	private float mDefaultV = 1.067f;
	private float mDefaultD = 7.931f;
//	private float mDefaultT = 4.5f;
	private float mDefaultT = 0.0f;

	public ReceivedDataAnalysis() {

	}

	public ReceivedDataAnalysis(float defaultA, float defaultV, float defaultD, float defaultT) {
		mDefaultA = defaultA;
		mDefaultV = defaultV;
		mDefaultD = defaultD;
		mDefaultT = defaultT;

	}

	public float[] getWaveFloatData() {
		int JumpByteN = 10;
		short plb;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			float mean = 0;// 骞冲潎鍊硷紱
			int i;
			for (i = 0; i < mReceiveWaveFloatData.length; i++) {
				plb = mReceiveBytes[i * 2 + JumpByteN];
				plb = (short) (int) ((plb << 8) & 0xff00);

				plb += mReceiveBytes[i * 2 + JumpByteN + 1] & 0xff;
				float a = plb;
				// if(true)Log.d(TAG, "getWaveFloatData() 1 a = "+a
				// +","+mReceiveBytes[i*2+JumpByteN]+","+mReceiveBytes[i*2+JumpByteN+1]);

				if (getVoValue(a) < -1 || getVoValue(a) > 1)
					mReceiveWaveFloatData[i] = getVoValue(a);

				mReceiveWaveFloatData[i] = getVoValue(a);
				mean += mReceiveWaveFloatData[i] / ((float) mReceiveWaveFloatData.length);
			}
			;

			for (i = 0; i < mReceiveWaveFloatData.length; i++)
				mReceiveWaveFloatData[i] -= mean;
			;

			break;
		}
		return mReceiveWaveFloatData;

	}
	public float[] getWaveFloatData(int cypl) {
		int JumpByteN = 10;
		int lhg=0;
		if (cypl>=2560)
		{
			lhg=cypl/2560-1;
		}
		short plb;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			float mean = 0;// 骞冲潎鍊硷紱
			int i;
			if (lhg>0)
			{
				int k=0;
				for (i = 0; i < mReceiveWaveFloatData.length/(1+lhg); i++) 
				{
					plb = mReceiveBytes[i * 2 + JumpByteN];
					plb = (short) (int) ((plb << 8) & 0xff00);

					plb += mReceiveBytes[i * 2 + JumpByteN + 1] & 0xff;
					float a = plb;

					for (int j = 0; j <= lhg; j++)
					{
						mReceiveWaveFloatData[k] = getVoValue(a);
						mean += mReceiveWaveFloatData[i+j] / ((float) mReceiveWaveFloatData.length);
						k++;
					}
					
				}
			}
			else 
			{
				for (i = 0; i < mReceiveWaveFloatData.length; i++) {
					plb = mReceiveBytes[i * 2 + JumpByteN];
					plb = (short) (int) ((plb << 8) & 0xff00);

					plb += mReceiveBytes[i * 2 + JumpByteN + 1] & 0xff;
					float a = plb;
					// if(true)Log.d(TAG, "getWaveFloatData() 1 a = "+a
					// +","+mReceiveBytes[i*2+JumpByteN]+","+mReceiveBytes[i*2+JumpByteN+1]);

					if (getVoValue(a) < -1 || getVoValue(a) > 1)
						mReceiveWaveFloatData[i] = getVoValue(a);

					mReceiveWaveFloatData[i] = getVoValue(a);
					mean += mReceiveWaveFloatData[i] / ((float) mReceiveWaveFloatData.length);
				}
			}
//			for (i = 0; i < mReceiveWaveFloatData.length; i++) {
//				plb = mReceiveBytes[i * 2 + JumpByteN];
//				plb = (short) (int) ((plb << 8) & 0xff00);
//
//				plb += mReceiveBytes[i * 2 + JumpByteN + 1] & 0xff;
//				float a = plb;
//				// if(true)Log.d(TAG, "getWaveFloatData() 1 a = "+a
//				// +","+mReceiveBytes[i*2+JumpByteN]+","+mReceiveBytes[i*2+JumpByteN+1]);
//
//				if (getVoValue(a) < -1 || getVoValue(a) > 1)
//					mReceiveWaveFloatData[i] = getVoValue(a);
//
//				mReceiveWaveFloatData[i] = getVoValue(a);
//				mean += mReceiveWaveFloatData[i] / ((float) mReceiveWaveFloatData.length);
//			}
//			;

			for (i = 0; i < mReceiveWaveFloatData.length; i++)
				mReceiveWaveFloatData[i] -= mean;
			;

			break;
		}
		return mReceiveWaveFloatData;

	}
	float[] mFFTY = null;

	/**
	 * ffT 鍚庣殑Y杞存暟鎹�
	 * 
	 * @return
	 */
	public float[] getFFTDataArrayY() {
		int SamplePoint = caiyangdian;// 采样点数
		mFFTY= new float[SamplePoint];// y即为纵坐标值
		mFFTY=_dataAnalysis.getFFTDataArrayY(/*mDLCmd, */caiyangdian, caiyangPinLv, mFFTY, mReceiveWaveFloatData);
//		return _dataAnalysis.getFFTDataArrayY(/*mDLCmd, */caiyangdian, caiyangPinLv, mFFTY, mReceiveWaveFloatData);
		return mFFTY;
	}

	private final static float mBASEDATA = 2.56f;

	/**
	 * ffT 鍚庣殑X杞存暟鎹�
	 * 
	 * @return
	 */
	public float[] getFFTDataArrayX() {
		return _dataAnalysis.getFFTDataArrayX(/*mDLCmd, */ caiyangdian, caiyangPinLv, mBASEDATA);
	}

	// public double[] getFFTDataArrayX() {
	// int SamplePoint = caiyangdian;// 閲囨牱鐐规暟
	// Complex[] InputData = new Complex[SamplePoint];
	// int i;
	// for (i = 0; i < SamplePoint; i++) {
	// InputData[i] = new Complex(mReceiveWaveFloatData[i], 0);
	// }
	//
	// Complex[] YM = FFT.fft(InputData);// 姹傚箙鍊�
	// double[] y = new double[SamplePoint];// y鍗充负绾靛潗鏍囧��
	// for (i = 0; i < SamplePoint; i++) {
	// y[i] = YM[i].abs() * 2 / ((double) SamplePoint);
	// }
	// y鍗充负绾靛潗鏍囷紝涓巟鍧愭爣鐨勫叧绯诲涓�:
	// SampleFre涓洪噰鏍烽鐜�
	// int SpectralLineLen = (int) (((double) SamplePoint) / 2.56);// 璋辩嚎鏁�
	// double x[] = new double[SpectralLineLen];// x杞村潗鏍囥��
	// if(mDLCmd == BluetoothConstast.CMD_Type_CaiJi){
	//
	// double Resulation = caiyangPinLv / ((double) SamplePoint);// 棰戠巼鍒嗚鲸鐜�
	//
	// for (int k = 0; k < SpectralLineLen; k++) {
	// x[k] = k * Resulation;
	// }
	// }
	// return x;
	//
	// }

	// 鑾峰彇杞存暟
	public int getSensorType() {
		return mReceiveBytes[5];
	}

	float getVoValue(float v) {
		float value = 0f;
		float mstandardMv = mDefaultA;

		int macceleratedSpeed = 10;
		value = v;
		// if(true)Log.d(TAG, "getVoValue() 1 value = "+value);
		value /= 65536 / 5000;

		if (getSensorType() == Constants.CMD_Sensor_Type_JiaSuDu) {
			value = value * macceleratedSpeed / mstandardMv;
		} else if (getSensorType() == Constants.CMD_Sensor_Type_SuDu) {
			value = value * macceleratedSpeed * mDefaultV / mstandardMv;
		} else if (getSensorType() == Constants.CMD_Sensor_Type_WeiYi) {
			value = value * macceleratedSpeed * mDefaultD / mstandardMv;
		}

		if (true)
			Log.d(TAG, "getVoValue()value = " + value);
		return value;
	}

	/**
	  * 
	  */

	/**
	 * 鏈夋晥鏁板�兼垨娓╁害鎴栦紶鎰熷櫒鐨勮酱鏁�
	 * 
	 * @return
	 */
	public float getValidValue() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			dValue = getZhouShu();
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.getValidValue(/*mDLCmd, */ mReceiveWaveFloatData);
			break;
//		case Constants.CMD_Type_GetTemper:
//			dValue = getTemperature();
//			break;
		case Constants.CMD_Type_CaiJiZhuanSu:
			dValue = getZhuanSu();
			break;
		}

		if (true)
			Log.d(TAG, "getValidValue()dValue = " + dValue);
		return (float) dValue;
	}

	private int getZhouShu() {
		int zhoushu = 0;
		if (mReceiveBytes[2] == (byte) 0xd2) {
			zhoushu = mReceiveBytes[3];
		}
		return zhoushu;
	}

	public float getZhuanSu() {
		float zhuansu = 0;
		if (mReceiveBytes[2] == (byte) 0xd3) {
			byte[] tempByte = new byte[4];
			System.arraycopy(mReceiveBytes, 3, tempByte, 0, tempByte.length);
			zhuansu = SystemUtil.ByteArrayToFloat(tempByte);
		}
		return zhuansu;
	}

	/**
	 * 宄板��
	 * 
	 * @return
	 */
	public float getFabsMaxValue() {
		float dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.getFabsMaxValue(/*mDLCmd, */mReceiveWaveFloatData);
			break;
		}

		if (true)
			Log.d(TAG, "getFabsMaxValue()dValue = " + dValue);
		return dValue;
	}

	/**
	 * 鑾峰彇宄板嘲鏁板��
	 * 
	 * @return
	 */
	public float getFengFengValue() {
		float dValue = 0;
		float nValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.getFengFengValue(/*mDLCmd, */ mReceiveWaveFloatData);
			break;
		}

		if (true)
			Log.d(TAG, "getFengFengValue()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 裕度指标
	 * 
	 * @return
	 */
	public double GetClearanceFactor() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetClearanceFactor(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetClearanceFactor()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 峭度指标
	 * 
	 * @return
	 */
	public double GetKurtosisFactor() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetKurtosisFactor(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetKurtosisFactor()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 斜度
	 * 
	 * @return
	 */
	public double GetSlope() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetSlope(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetSlope()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 峭度
	 * 
	 * @return
	 */
	public double GetKurtosis() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetKurtosis(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetKurtosis()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 波形指标
	 * 
	 * @return
	 */
	public double GetWaveFactor() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetWaveFactor(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetWaveFactor()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 峰值指标
	 * 
	 * @return
	 */
	public double GetPeakFactor() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetPeakFactor(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetPeakFactor()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 脉冲指标
	 * 
	 * @return
	 */
	public double GetPulseFactor() {
		double dValue = 0;
		switch (mDLCmd) {
		case Constants.CMD_Type_ReadSensorParams:
			break;
		case Constants.CMD_Type_CaiJi:
			dValue=_dataAnalysis.GetPulseFactor(mReceiveWaveFloatData,caiyangdian);
			break;
		}

		if (true)
			Log.d(TAG, "GetPulseFactor()dValue = " + dValue);
		return dValue;
	}
	/**
	 * 
	 * @param strbyte
	 * @return
	 */
	private byte getCMDTypeFromFirstReceivedPacageData(byte[] strbyte) {
		byte cmd = 0;
		int StrHeadLen = Constants.VibrationHead.length();
		byte[] ByteHeadData = new byte[Constants.VibrationHead.length() / 2];

		if (strbyte.length < 4)
			return 0;

		System.arraycopy(strbyte, 0, ByteHeadData, 0, ByteHeadData.length);
		String strx = SystemUtil.bytesToHexString(ByteHeadData).toLowerCase();
		if (strx.equals(Constants.VibrationHead))
			cmd = Constants.CMD_Type_CaiJi;
		else if (strx.substring(0, StrHeadLen - 2).equals(Constants.OtherParaHead))
			cmd = Constants.CMD_Type_ReadSensorParams;
		else if (strx.substring(0, StrHeadLen - 2).equals(Constants.TemperHead))
			cmd = Constants.CMD_Type_GetTemper;
		else if (strx.substring(0, StrHeadLen - 2).equals(Constants.ChargeHead))
			cmd = Constants.CMD_Type_GetCharge;
		else if (strx.substring(0, StrHeadLen - 2).equals(Constants.ShaftsHead))
			cmd = Constants.CMD_Type_CaiJiZhuanSu;
		else
			cmd = 0;
		;
		return cmd;
	}

	/**
	 * 鎺ュ彈鑾峰彇鍒扮殑BLE鏁版嵁
	 * 
	 * @param strbyte
	 */

	// 判断CRC校验
	private boolean IsCRC32OK(byte[] strbyte) {
		long LongWidth = Long.SIZE >> 4;

		CRC32 crc = new CRC32();

		if ((strbyte.length - LongWidth) >= LongWidth)
			crc.update(strbyte, 0, strbyte.length - (int) LongWidth);
		else
			return false;
		;

		byte[] crcLoadV = new byte[(int) LongWidth];
		System.arraycopy(strbyte, strbyte.length - (int) LongWidth, crcLoadV, 0, (int) LongWidth);

		if (((int)crc.getValue()==HexUtil.getInt(crcLoadV)))
			return true;
		else
			return false;
	}

	public int getDataFromBLE(byte[] strbyte, byte MeasurementType) {

		if (strbyte[0] != (byte) 0x7D) {
			return Constants.Error_HeaderUnmatch;
		}

		mDLCmd = getCMDTypeFromFirstReceivedPacageData(strbyte);
		if (mDLCmd == (byte) 0x00) {
			return Constants.Error_CommandUnmatch;
		}

		switch (mDLCmd) {
		case Constants.CMD_Type_CaiJi: // 振动
			if (strbyte[0] != (byte) 0x7D || strbyte[1] != (byte) 0x7D || strbyte[2] != (byte) 0x7D || strbyte[3] != (byte) 0x7D) {
				return Constants.Error_HeaderUnmatch;
			}
			break;
		case Constants.CMD_Type_CaiJiZhuanSu: // 转速
			if (strbyte[0] != (byte) 0x7D || strbyte[1] != (byte)0x14 || strbyte[2] != (byte) 0xD3) {
				return Constants.Error_HeaderUnmatch;
			}
			break;
		case Constants.CMD_Type_GetTemper: // 温度
			if (strbyte[0] != (byte) 0x7D || strbyte[1] != (byte) 0x14 || strbyte[2] != (byte) 0xD6) {
				return Constants.Error_HeaderUnmatch;
			}
			break;
		case Constants.CMD_Type_GetCharge: // 电池电量
			if (strbyte[0] != (byte) 0x7D || strbyte[1] != (byte) 0x14 || strbyte[2] != (byte) 0xD7) {
				return Constants.Error_HeaderUnmatch;
			}
			break;
		}

		if (!IsCRC32OK(strbyte)) {
			return Constants.Error_CRCUnmatch;
		}

		boolean nRe = true;
		if (strbyte.length < Constants.EveryPackageLen) {
			return Constants.Error_LengthUnmatch;
		}

		if (mReceiveBytes != null) {
			mReceiveBytes = null;
		}

		switch (mDLCmd) {
		case Constants.CMD_Type_CaiJi: // 振动
			if (MeasurementType != Constants.CMD_Type_CaiJi) {
				return Constants.Error_CommandUnmatch;
			}
			caiyangdian = (strbyte[6] << 8) & 0xff00 | strbyte[7] & 0xff;
			if (caiyangdian % 256 != 0 || caiyangdian < 256) {
				return Constants.Error_OtherUnmatch;
			}
			caiyangPinLv = (strbyte[8] << 8) & 0xff00 | strbyte[9] & 0xff;
			if (caiyangPinLv < 256 || caiyangPinLv > 8192) {
				return Constants.Error_OtherUnmatch;
			}
			mAxCounts = strbyte[4]; // 暂时不用
			if (mReceiveWaveFloatData != null) {
				mReceiveWaveFloatData = null;
			}
			mReceiveWaveFloatData = new float[caiyangdian];

			mShoudReceivedByteSizes = caiyangdian * 2 + 10 + 9 + 9 + 3 * 4;
			if (mShoudReceivedByteSizes != strbyte.length) {
				return Constants.Error_LengthUnmatch;
			}
			mReceiveBytes = new byte[mShoudReceivedByteSizes];
			break;
		// case BluetoothConstast.CMD_Type_ReadSensorParams://读传感器参数，目前主要是轴信息
		// {
		// return false;
		// }
		case Constants.CMD_Type_CaiJiZhuanSu: // 转速
		case Constants.CMD_Type_GetTemper: // 温度
		case Constants.CMD_Type_GetCharge: { // 电池电量
			if (!(MeasurementType == Constants.CMD_Type_CaiJiZhuanSu || MeasurementType == Constants.CMD_Type_GetTemper || MeasurementType == Constants.CMD_Type_GetCharge)) {
				return Constants.Error_CommandUnmatch;
			}
			mShoudReceivedByteSizes = strbyte.length;
			mReceiveBytes = new byte[mShoudReceivedByteSizes];
			break;
		}
		default:
			return Constants.Error_CommandUnmatch;
			// break;
		}

		try {

			System.arraycopy(strbyte, 0, mReceiveBytes, 0, strbyte.length);
			mReceivedDataByteSizes += strbyte.length;

		} catch (Exception e) {
			e.printStackTrace();
			nRe = true;
		}

		return 0;
	}

	/**
	 * 閲嶇疆鏁版嵁
	 */
	public void reset() {
		if (mReceiveWaveFloatData != null) {
			mReceiveWaveFloatData = null;
		}
		mReceivedDataByteSizes = 0;
		mReceivedPackageCounts = 0;
		caiyangdian = 0;
		mAxCounts = 0;
		if (mReceiveBytes != null) {
			mReceiveBytes = null;
		}
	}

//	/**
//	 * 鑾峰彇娓╁害鏁板��
//	 */
//	public float getTemperature() {
//		float tem = -300;// -300琛ㄧず鏃犳晥鐨勬俯搴�
//		if (mReceiveBytes[2] == (byte) 0xd6) {
//			byte[] tempByte = new byte[Float.SIZE >> 3];
//			System.arraycopy(mReceiveBytes, 3, tempByte, 0, tempByte.length);
//			// tem=SystemUtil.ByteArrayToFloat(tempByte);
//
//			tem = VConvertTemp(tempByte) + mDefaultT;
//
//		}
//
//		return tem;
//
//	}
//
//	float VConvertTemp(byte[] tempByte) {
//		//long plb=(0xff & tempByte[3]) | (0xff00 & (tempByte[2] << 8)) | (0xff0000 & (tempByte[1] << 16));
//    	long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
//    	plb>>=8;
//		float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
//		//if(tem<1||tem>4.9)
//			//return -300;
//		
////		double nValue=tem+2.5;//2016-03-24 liuhg修改前原程序
////		nValue=-1075.9958518686519*Math.pow(nValue,6.0)+11257.5268432685*Math.pow(nValue,5.0)-48793.64089237545*Math.pow(nValue,4.0)+112306.83506548179*Math.pow(nValue,3.0)-145026.68311658205*Math.pow(nValue,2.0)+99966.887047342723*Math.pow(nValue,1.0)-28796.070315616675;
////	        nValue+=25.0;//2016-03-24 liuhg修改前原程序
////	        ;
////		tem=(float)nValue;//2016-03-24 liuhg修改前原程序
//		
//		double nValue=(tem+2.5)*1000;//2016-03-24 liuhg修改
//		tem=(float) m_CubicSpline.Interpolate(nValue);//2016-03-24 liuhg修改
//		
//		if(tem>300||tem<-50) //传感器最多能测到300度。
//			tem=-300; 	
//    	return tem;
//	}
//	/**
//	 * 获取温度数值
//	 */
////    float getTemperature(){  
//   public float getTemperature(){ 
//    	DecimalFormat df = new DecimalFormat("#.00");//保留两位小数  2016-04-06 liuhg添加
//    	
//    	float tem=-300;//-300表示无效的温度
////		if(mReceiveBytes[2]==(byte)0xd6){//2016-04-05 liuhg修改前原程序
////			byte[]tempByte=new byte[Float.SIZE>>3];
////			System.arraycopy(mReceiveBytes, 3, tempByte, 0, tempByte.length);
////		//	tem=SystemUtil.ByteArrayToFloat(tempByte);
////			
////			 tem=VConvertTemp(tempByte)+mDefaultT;
////		
////		}
//    	
//    	if(mReceiveBytes[2]==(byte)0xd6){//2016-04-05 liuhg修改
//    		byte[]tempByte=new byte[Float.SIZE>>3];
//    		System.arraycopy(mReceiveBytes, 3, tempByte, 0, tempByte.length);
//    		if (mReceiveBytes[7]==(byte)0x00) {
//    			if((int)VConvertTemp(tempByte)!=-300)//2016-05-26 liuhg修改
//    			{
//    			 tem=Float.parseFloat(df.format(VConvertTemp(tempByte)+mDefaultT));
//    			}
////    			tem=Float.parseFloat(df.format(VConvertTemp(tempByte)+mDefaultT));//2016-05-26 liuhg修改前原程序
//			}
//    		else if (mReceiveBytes[7]==(byte)0xff) {//传感器不含温度测量
//    			tem=(float) -300.00;
//			}
//    		else {//PT100或PT1000
//    			String aa=df.format(PTConvertTemp(tempByte, mReceiveBytes[7])+mDefaultT);
//    			tem= Float.parseFloat(aa);
//			}
//			
//		
//		}
//		
//		
//		return tem;
//		
//	}
//   public float getTemperature(int mTempCount,int mAverageCount,float[]TempuratureData,float mEmissivity)
   public double[] getTemperature(double mEmissivity)
   { 
	   double[] dbValue = new double[2];
	   double Tm; //测量温度
	   double Adjust1=0.001*(1-mEmissivity); //调整系数1
	   double Adjust2;//调整系数2
	   double MinM=-20; //最低温度；
	   double MaxM=300; //最高温度。
	   double Tobj=-300; //目标温度。
	   double n=4.0;//固定值。
	   double Tatm=25;//环境温度
	   double InvalidValue=-300;//测量的温度无效时返回的值
	   double nValue=-300;
	   
	   	DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
	   	if(mReceiveBytes[2]==(byte)0xd6){
	   		byte[]tempByte=new byte[Float.SIZE>>3];
	   		System.arraycopy(mReceiveBytes, 3, tempByte, 0, tempByte.length);
	   		if (mReceiveBytes[7]==(byte)0x00) {
	   			
	   			long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
	   	    	plb>>=8;
	   			float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
	   			nValue=(tem+2.5)*1000;
	   			
	   			Tm=Double.parseDouble(df.format(VConvertTemp(nValue)));
	   			Adjust2=(Tm-100)*0.050/320;
	   			if(Tm<=100)
	   				Adjust2=0;
	   			
	   			if(Tm<MaxM)
	   			{
	   			  if((Tm+273.15-Math.pow((1-mEmissivity),1/n)*(Tatm+273.15))>0)
	   			    Tobj=Math.pow((1/(mEmissivity-Adjust1-Adjust2))*(Math.pow(Tm+273.15,n)-(1-mEmissivity)*Math.pow(Tatm+273.15,n)),1/(n))-273.15;
	   			}
	   			else
	   			{
	   				dbValue[0]=nValue;
	   			   	dbValue[1]=MaxM;
	   			   	return dbValue;
//	   			  return MaxM;
	   			}

	   		    if(Tobj<MinM)
	   		    {
	   		    	dbValue[0]=nValue;
	   			   	dbValue[1]=MinM;
	   			   	return dbValue;
//	   				return InvalidValue;
	   		    }
	   		    Tobj+=mDefaultT;
			}
	   		else if (mReceiveBytes[7]==(byte)0x80) {
	   			
	   			byte[]tempByte_wenbu=new byte[Float.SIZE>>3];
				System.arraycopy(mReceiveBytes, 8, tempByte_wenbu, 0, tempByte_wenbu.length);
				
	   			long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
	   	    	plb>>=8;
	   			float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
	   			nValue=(tem+2.5)*1000;
	   			
	   			Tm=Double.parseDouble(df.format(VConvertTemp(nValue)));
	   			Adjust2=(Tm-100)*0.050/320;
	   		 
	   			Tatm=GetTatmFromVoltageatm(VConvertEnvironmentVoltage(tempByte_wenbu));
	   			addLog("环境温度="+Tatm);
	   		
	   			if(Tm<=100)
	   				Adjust2=0;
	   			
	   			if(Tm<MaxM)
	   			{
	   			  if((Tm+273.15-Math.pow((1-mEmissivity),1/n)*(Tatm+273.15))>0)
	   			    Tobj=Math.pow((1/(mEmissivity-Adjust1-Adjust2))*(Math.pow(Tm+273.15,n)-(1-mEmissivity)*Math.pow(Tatm+273.15,n)),1/(n))-273.15;
	   			}
	   			else
	   			{
	   				dbValue[0]=nValue;
	   			   	dbValue[1]=MaxM;
//	   			   	return dbValue;
//	   			  return MaxM;
	   			}

	   		    if(Tobj<MinM)
	   		    {
	   		    	dbValue[0]=nValue;
	   			   	dbValue[1]=InvalidValue;
//	   			   	return dbValue;
//	   				return InvalidValue;
	   		    }
	   		 Tobj=TempAdjust((float)Tobj,(float)Tatm)+mDefaultT;
//	   		    Tobj+=mDefaultT;
			}
	   		else if(mReceiveBytes[7]==(byte)0x01||mReceiveBytes[7]==(byte)0x02)//PT100或PT1000
			{
	   			long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
	   	    	plb>>=8;
	   			float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
	   			nValue=(float) ((float) (tem+2.5)/40);
	   			
				String aa=df.format(PTConvertTemp(nValue, mReceiveBytes[7])+mDefaultT);
				Tobj= Double.parseDouble(aa);
			}
		}
	   	dbValue[0]=nValue;
	   	dbValue[1]=Tobj;
//	   	return Tobj;
	   	return dbValue;
	}
 //Tobj物体温度；Tatm为环境温度
   float TempAdjust(float Tobj,float Tatm)
   {
   float OffsetTemp=0;
   float RealTemp = -300;
   float k;
   int ii;

   //-40,-30,-20,-10,0,....,..70为环境温度。
   float  TempCoords[][]={{-40,28.5f},{-30,23},{-20,17.5f},{-10,13},{0,9},{10,5},{20,0.8f},{25,0},{30,-0.6f},{40,-2.5f},{50,-3.5f},{60,-4.5f},{70,-2}};
   int ArrayLen=TempCoords.length; 

   //不在环境范围之内，直接赋值退出。
   if(TempCoords[0][0]>Tatm||TempCoords[ArrayLen-1][0]<Tatm)
   	 return Tobj;
     ;
   for( ii=0;ii<ArrayLen-1;ii++)
   {
   	  if(TempCoords[ii][0]<=Tatm&&TempCoords[ii+1][0]>=Tatm)
   	  {
   	    k=(TempCoords[ii+1][1]-TempCoords[ii][1])/(TempCoords[ii+1][0]-TempCoords[ii][0]);
   	    OffsetTemp=k*(Tatm-TempCoords[ii][0])+TempCoords[ii][1];
   		break;
   	  }
   }
   ;

   if(ii<ArrayLen-1)
   {
   //-20,-10,0,10,20,....为物体温度。
     float TobjCoords[][]={{-20,1},{-10,0.95f},{0,0.90f},{10,0.85f},{20,0.80f},{30,0.75f},{40,0.7f},{50,0.655f},{60,0.61f},{70,0.565f},{80,0.510f},{90,0.47f},{100,0.44f},
     {110,0.41f},{120,0.38f},{130,0.35f},{140,0.32f},{150,0.29f},{160,0.26f},{170,0.23f},{180,0.21f},{190,0.19f},{200,0.17f},{210,0.15f},{220,0.13f},{230,0.12f},{240,0.11f}};
   	ArrayLen=TobjCoords.length; 
   	if(TobjCoords[0][0]>Tobj||TobjCoords[ArrayLen-1][0]<Tobj)
   		return Tobj;
   	;
   	 for( ii=0;ii<ArrayLen-1;ii++)
   	 {
   	  if(TobjCoords[ii][0]<=Tobj&&TobjCoords[ii+1][0]>=Tobj)
   	  {
   	    k=(TobjCoords[ii+1][1]-TobjCoords[ii][1])/(TobjCoords[ii+1][0]-TobjCoords[ii][0]);
   	    RealTemp=k*(Tobj-TobjCoords[ii][0])+TobjCoords[ii][1];
   		RealTemp*=OffsetTemp;
   		RealTemp=Tobj-RealTemp;
   		break;
   	  };
   		
   	 }
   	;

   	if(ii>=ArrayLen-1)
   		 return Tobj;
   	;
   }
   else
     return Tobj;
    ;

   return RealTemp;
   }
   float VConvertEnvironmentVoltage(byte[]tempByte)
   {
	   	long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
	   	plb>>=8;
		addLog("环境温度对应的电压="+plb);
	   	return plb;
   }
   @SuppressWarnings("unchecked")
	public static void addLog(String log) {
		try {
			boolean flag=false;
			flag=(Boolean) CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Print);
			if (flag)
			{
				CustomListAdapter adapter = (CustomListAdapter) CacheControl.GetInstance().get(CacheControl.Key_Log);
				synchronized (adapter) {
					if (adapter.getCount() >= 20) {
						adapter.remove(adapter.getItem(0));
					}
					adapter.add(log);
				}
			}
		} catch (Exception e) {
			LogUtil.GetInstance().append(e);
		}
	}
   /**
    * 从环境电压得到环境温度。
   * @param Voltageatm 环境电压
   * @return 返回值-300为无效
   */
  public float GetTatmFromVoltageatm(float Voltageatm)
   {
     float k;
     float Tamp=25;

     float[][]  VoltageCoords={{857,-40},{872,-30},{889,-20},{908,-10},{930,-5},{959,0},{993,5},{1039,10},{1092,15},{1126,20},{1210,25},{1267,30},{1337,35},{1445,40},{1534,45},{1650,50},{1881,60},{2143,70}};
     int ArrayLen=VoltageCoords.length; 
       //不在环境范围之内，直接赋值退出。
     if(VoltageCoords[0][0]>Voltageatm)
   	  return -300;
   	  ;
     if(VoltageCoords[ArrayLen-1][0]<Voltageatm)
   	  return -300;

     ;
     for(int ii=0;ii<ArrayLen-1;ii++)
     {
   	  if(VoltageCoords[ii][0]<=Voltageatm&&VoltageCoords[ii+1][0]>=Voltageatm)
   	  {
   	    k=(VoltageCoords[ii+1][1]-VoltageCoords[ii][1])/(VoltageCoords[ii+1][0]-VoltageCoords[ii][0]);
   	    Tamp=k*(Voltageatm-VoltageCoords[ii][0])+VoltageCoords[ii][1];
   		break;
   	  }
     }
     ;
     return Tamp;
   }
//    float PTConvertTemp(byte[]tempByte,int PT)//2016-04-05 liuhg添加 PT100或PT1000传感器阻值转温度
  float PTConvertTemp(double V0,int PT)
    {
    	float tempurature;
//    	long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
//    	plb>>=8;
//		float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
//		float V0=(float) ((float) (tem+2.5)/40);
		float RT=(float) (V0*CubicSpline.Resistance/(2.5-V0));
		if (PT==1) {//PT100温度传感器
			tempurature= tx_temp_pt100(RT);
		}
		else if (PT==2) {//PT1000温度传感器
			tempurature= tx_temp_pt1000(RT);
		}
		else {
			tempurature= (float) -300;
		}
		return tempurature;
    }
    float tx_temp_pt100(float value)//2016-04-05 liuhg添加 PT100传感器测量的温度
    {

    	float Temp = -300;
    	int length=CubicSpline.PT100Array.length;
    	if (value<CubicSpline.PT100Array[0]) {
			value=-200;
			Temp= value;
		}
    	else if (value>CubicSpline.PT100Array[length-1]) {
    		value=660;
    		Temp= value;
		}
    	else {
    		for( int ii=0 ; ii < length-1 ; ii++)
       	 	{
	       		if(value >= CubicSpline.PT100Array[ii]  && value <= CubicSpline.PT100Array[ii+1])
	       		{
	       			Temp=(float) (ii-199-(CubicSpline.PT100Array[ii+1]-value)/(CubicSpline.PT100Array[ii+1]-CubicSpline.PT100Array[ii]));
	       		}
       	 	}
    		
//    		return Temp;
		}
		return Temp;	 
    }
    float tx_temp_pt1000(float value)//2016-04-05 liuhg添加 PT1000传感器测量的温度
    {
    	float Temp = -300;
    	int length=CubicSpline.PT1000Array.length;
    	if (value<CubicSpline.PT1000Array[0]) {
			value=-50;
			return value;
		}
    	else if (value>CubicSpline.PT100Array[length-1]) {
    		value=200;
    		return value;
		}
    	else {
    		for( int ii=0 ; ii < length-1 ; ii++)
       	 	{
	       		if(value >= CubicSpline.PT1000Array[ii]  && value <= CubicSpline.PT1000Array[ii+1])
	       		{
	       			Temp=(float) (ii-49-(CubicSpline.PT1000Array[ii+1]-value)/(CubicSpline.PT1000Array[ii+1]-CubicSpline.PT1000Array[ii]));
	       		}
       	 	}
    		return Temp;
		}	 
    }
//    float VConvertTemp(byte[]tempByte)
//    {
//    	long plb=(0xff00 & (tempByte[3]<<8)) | (0xff0000 & (tempByte[2] << 16)) | (0xff000000 & (tempByte[1] << 24));
//    	plb>>=8;
//		float tem=(float)(((double)plb)*5/Math.pow(2.0, 24.0));		
//		double nValue=(tem+2.5)*1000;//2016-03-24 liuhg修改
//		
//		tem=(float) m_CubicSpline.Interpolate(nValue);//2016-03-24 liuhg修改	
//		if(tem>331||tem<-32) //传感器最多能测到331度。//2016-05-26 liuhg修改
//			tem=-300; 
//    	return tem;
//    }
    float VConvertTemp(double nValue)
    {
		float tem=-300f;
		tem=(float) m_CubicSpline.Interpolate(nValue);//2016-03-24 liuhg修改	
		if(tem>331||tem<-32) //传感器最多能测到331度。//2016-05-26 liuhg修改
			tem=-300; 
    	return tem;
    }
	public FreDomainPara[] getMaxFD() {
		return _dataAnalysis.getMaxFD(mFFTY, caiyangdian, caiyangPinLv);
	}

	// FFTData --FFT鍙樻崲鍚庣殑鏁版嵁,瀵瑰簲浣爕,
	// SampleFre--閲囨牱棰戠巼, 瀵瑰簲浣燾aiyangPinLv
	// SamplePoint--閲囨牱鐐规暟, SamplePoint
	private FreDomainPara[] GetMaxFreDomainPara(float[] FFTData, float SampleFre, int SamplePoint) {
		int ArraySize = 4;
		int FFTDataLen = FFTData.length;
		if (FFTDataLen <= ArraySize)
			return null;
		;
		FreDomainPara[] m_FreDomainPara = new FreDomainPara[ArraySize];

		int i;
		float temp;

		for (i = 0; i < ArraySize; i++) {
			m_FreDomainPara[i] = new FreDomainPara();
			m_FreDomainPara[i].M = 0;
			m_FreDomainPara[i].Fre = 0;

		}
		;

		m_FreDomainPara[0].M = FFTData[0];

		float Resulation = SampleFre / ((float) SamplePoint);// 棰戠巼鍒嗚鲸鐜�

		for (i = 1; i < FFTDataLen; i++) {
			temp = FFTData[i];
			if (temp >= m_FreDomainPara[0].M) {
				m_FreDomainPara[1].M = m_FreDomainPara[0].M;
				m_FreDomainPara[1].Fre = m_FreDomainPara[0].Fre;
				m_FreDomainPara[0].M = temp;
				m_FreDomainPara[0].Fre = i;
			} else if ((temp < m_FreDomainPara[0].M) && (temp >= m_FreDomainPara[1].M)) {
				m_FreDomainPara[2].M = m_FreDomainPara[1].M;
				m_FreDomainPara[2].Fre = m_FreDomainPara[1].Fre;
				m_FreDomainPara[1].M = temp;
				m_FreDomainPara[1].Fre = i;
			} else if ((temp < m_FreDomainPara[1].M) && (temp >= m_FreDomainPara[2].M)) {
				m_FreDomainPara[3].M = m_FreDomainPara[2].M;
				m_FreDomainPara[3].Fre = m_FreDomainPara[2].Fre;
				m_FreDomainPara[2].M = temp;
				m_FreDomainPara[2].Fre = i;
			} else if ((temp < m_FreDomainPara[2].M) && (temp >= m_FreDomainPara[3].M)) {
				m_FreDomainPara[3].M = temp;
				m_FreDomainPara[3].Fre = i;
			}
		}

		for (i = 0; i < ArraySize; i++) {
			m_FreDomainPara[i].Fre *= Resulation;
		}

		;
		return m_FreDomainPara;
	}

	boolean bTest = true;
	ByteArrayOutputStream _readBuffer = null;

	public boolean isValideData(byte[] readBuffer, byte sendCMD) {
		boolean returnValue = false;
		mReceiveBytes = readBuffer;
		mDLCmd = sendCMD;

		if (readBuffer != null && readBuffer.length >= 20) {
			switch (sendCMD) {
			case Constants.CMD_Type_CaiJi: {
				if (readBuffer[0] == (byte) 0x7d && readBuffer[1] == (byte) 0x7d && readBuffer[2] == (byte) 0x7d && readBuffer[3] == (byte) 0x7d) {
					returnValue = true;
					// if(SystemUtil.bytesToHexString(mReceiveBytes).substring(0,
					// 8).toLowerCase().equals("7d7d7d7d")){
					//
					// //CRC32鏍￠獙
					// CRC32 crc = new CRC32();
					// crc.update(mReceiveBytes, 0, mReceiveBytes.length-4);
					// String strGetCRC32 =Long.toHexString(crc.getValue());
					//
					// byte[]crcValue = new byte[4];
					// for(int i=0;i<4;i++){
					// crcValue[i]=mReceiveBytes[mReceiveBytes.length-4+i];
					// }
					// String sa=SystemUtil.bytesToHexString(crcValue);
					// if(sa.equals(strGetCRC32)){
					// returnValue=true;
					// }
					// Log.d(TAG," isValidate() strGetCRC32 is "+strGetCRC32
					// +"and calc CRC32 is "+sa);
				} else {
					Log.e(TAG, " isValidate() head data error");
				}

			}
				break;
			case Constants.CMD_Type_ReadSensorParams: {
				// if(SystemUtil.bytesToHexString(mReceiveBytes).substring(0,
				// 6).toLowerCase().equals("7d14d2")){
				if (readBuffer[0] == (byte) 0x7d && readBuffer[1] == (byte) 0x14 && readBuffer[2] == (byte) 0xd2) {
					returnValue = true;
				}
			}
				break;
			case Constants.CMD_Type_GetTemper: {
				// if(SystemUtil.bytesToHexString(mReceiveBytes).substring(0,
				// 6).toLowerCase().equals("7d14d6")){
				if (readBuffer[0] == (byte) 0x7d && readBuffer[1] == (byte) 0x14 && readBuffer[2] == (byte) 0xd6) {
					returnValue = true;
				}
			}
				break;
			case Constants.CMD_Type_GetCharge: {
				// if(SystemUtil.bytesToHexString(mReceiveBytes).substring(0,6).toLowerCase().equals("7d14d7")){
				if (readBuffer[0] == (byte) 0x7d && readBuffer[1] == (byte) 0x14 && readBuffer[2] == (byte) 0xd7) {
					returnValue = true;
				}
			}
				break;
			case Constants.CMD_Type_CaiJiZhuanSu: {
				// if(SystemUtil.bytesToHexString(mReceiveBytes).substring(0,
				// 6).toLowerCase().equals("7d14d3")){
				if (readBuffer[0] == (byte) 0x7d && readBuffer[1] == (byte) 0x14 && readBuffer[2] == (byte) 0xd3) {
					returnValue = true;
				}
			}
				break;
			}

		}

		if (true)
			Log.d(TAG, "isValidate()returnValue = " + returnValue);

		if (returnValue) {
			switch (mDLCmd) {
			case (byte) 0xd2:
			case (byte) 0xd3: {
				CRC32 crc = new CRC32();
				// crc.update(strbyte, 0, 16);
				// String s =Long.toHexString(crc.getValue());
				// byte[]crcValue = new byte[4];
				// for(int i=0;i<4;i++){
				// crcValue[i]=strbyte[strbyte.length-4+i];
				// }
				// String sa=SystemUtil.bytesToHexString(crcValue);
				// if(sa.equals(s)){
				// }
				// if(mReceiveBytes!=null){
				// mReceiveBytes=null;
				// }
				mShoudReceivedByteSizes = mReceiveBytes.length;
				// mReceiveBytes = new byte[mShoudReceivedByteSizes];
			}
				break;
			case (byte) 0xd1:
				caiyangdian = (mReceiveBytes[6] << 8) & 0xff00 | mReceiveBytes[7] & 0xff;
				caiyangPinLv = (mReceiveBytes[8] << 8) & 0xff00 | mReceiveBytes[9] & 0xff;
				mAxCounts = mReceiveBytes[4]; // 暂时不用

				mReceiveWaveFloatData = new float[caiyangdian];
				mShoudReceivedByteSizes = caiyangdian * 2 + 10 + 9 + 9 + 3 * 4;
				if (readBuffer.length != mShoudReceivedByteSizes) {
					returnValue = false;
				}

				break;
			case (byte) 0xd6: {
				CRC32 crc = new CRC32();
				crc.update(mReceiveBytes, 0, 16);
				String s = Long.toHexString(crc.getValue());
				byte[] crcValue = new byte[4];
				for (int i = 0; i < 4; i++) {
					crcValue[i] = mReceiveBytes[mReceiveBytes.length - 4 + i];
				}
				String sa = SystemUtil.bytesToHexString(crcValue);
				if (sa.equals(s)) {
				}
				mShoudReceivedByteSizes = mReceiveBytes.length;
			}
				break;
			}
		}
		return returnValue;
	}
//    public void InputTempPrams() {//2016-03-25 liuhg添加
//    	
//    	byte buffer[] = null;
//    	String path = Environment.getExternalStorageDirectory() + "/AIC8600/"+"BaseSetting/";
//    	String TempPramsName="CubicSplineName.txt";
//    	File f = new File(path+TempPramsName);
//        if(f.exists()){
//        	 try {  
//                 FileInputStream fin = new FileInputStream(path+TempPramsName);  
//                 if (fin!=null) {
//                     buffer = new byte[fin.available()];  
//                     fin.read(buffer);  
//                     fin.close();  
//				}
//             }  
//             catch (Exception e) {  
//                 e.printStackTrace();  
//             }
//        }
//        else {
//    		InputStream inputStream = CrashApplication.getApplication().getResources().openRawResource(R.raw.a);
//    		buffer = null;
//    		try {
//    			buffer = new byte[inputStream.available()];
//    		} catch (IOException e) {
//    			// TODO Auto-generated catch block
//    			e.printStackTrace();
//    		}
//    		try {
//    			inputStream.read(buffer);
//    		} catch (IOException e) {
//    			// TODO Auto-generated catch block
//    			e.printStackTrace();
//    		}
//		}
//		int FileLength = buffer.length;
//		if (FileLength > 0) {
//
//			byte pData[] = new byte[FileLength];
//			System.arraycopy(buffer, 0, pData, 0, FileLength);
//			if (!ParseStrToCubicSpline(pData, m_CubicSpline)) {
//				Toast.makeText(null, "曲线插值文件数据格式有误", Toast.LENGTH_LONG).show();
//			} else {
//
//			}
//		} else
//			Toast.makeText(null, "文件长度不能为空。", Toast.LENGTH_LONG).show();
//	}
	
	 public void InputTempPrams(String address,int type) //2016-03-25 liuhg添加
	    {
	    	//String strAddress=address.substring(0, address.indexOf("-"));
	    	String[] strbluetoothAddress=address.split(":");
	    	String bluetoothAddress = strbluetoothAddress[0];
	    	for (int i = 1; i < strbluetoothAddress.length; i++) {
	    		bluetoothAddress+=strbluetoothAddress[i];
			}
	    	
	    	Setting setting = new Setting();
	    	String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
	    	String TempPramsName = null;
	    	String NormalPramsName=null;
	    	TempPramsName=bluetoothAddress+"-temp.txt";
			NormalPramsName = bluetoothAddress + "-vibrate.txt";
			
			File fNormalPrams = new File(path + NormalPramsName);
			byte[] bufferNormalPrams = null;
			if (fNormalPrams.exists())
			{
				try {
					FileInputStream finNormalPrams = new FileInputStream(path+ NormalPramsName);
					if (finNormalPrams != null) {
						bufferNormalPrams = new byte[finNormalPrams.available()];
						finNormalPrams.read(bufferNormalPrams);
						finNormalPrams.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				int FileLengthNormal = bufferNormalPrams.length;
				if (FileLengthNormal>0) {
					String strMormalPrams = new String(bufferNormalPrams);
					String[] mormalPrams = strMormalPrams.split("\\*");
					if (mormalPrams.length<4) 
					{
						if (AICApplication.isTips){
							ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), NormalPramsName+"文件：参数不全，将调用默认参数");
						}
						Log.e(TAG, NormalPramsName+"文件：参数不全，将调用默认参数");
						getNormalPramsFromRaw();
					}
					else 
					{
						String[] shuju = new String[mormalPrams.length];
						for (int i = 0; i < mormalPrams.length; i++) {
							int start = mormalPrams[i].indexOf(":");
							int end = mormalPrams[i].length();
							shuju[i] = mormalPrams[i].substring(start + 1, end);
						}
						try {
							mDefaultT = Float.parseFloat(shuju[0].toString());
							mDefaultA = Float.parseFloat(shuju[1].toString());
							mDefaultV = Float.parseFloat(shuju[2].toString());
							mDefaultD = Float.parseFloat(shuju[3].toString());
							
							CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_A, shuju[1].toString());
							CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_V, shuju[2].toString());
							CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_D, shuju[3].toString());
							CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_T, shuju[0].toString());
							
						} catch (Exception e) {
							// TODO: handle exception
							//Toast.makeText(null, NormalPramsName+"文件：校准数据格式有误，将调用默认参数", 0).show();
							Log.e(TAG, NormalPramsName+"文件：校准数据格式有误，将调用默认参数");
							ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), "文件：校准数据格式有误，将调用默认参数");
							getNormalPramsFromRaw();
						}
					}
				}
			} 
			else 
			{
				//Toast.makeText(null, "未找到参数配置文件"+NormalPramsName+"，将启用默认配置", 0).show();
				Log.e(TAG, "未找到参数配置文件"+NormalPramsName+"，将启用默认配置");
				ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), "未找到参数配置文件"+NormalPramsName+"，将启用默认配置");
				getNormalPramsFromRaw();
			}

			byte[] bufferTemp = null;
			if (type==CommonDef.checkUnit_Type.TEMPERATURE) {//测温
		    	File fTemp = new File(path+TempPramsName);
		        if(fTemp.exists())
		        {
		        	 try 
		        	 {  
		                 FileInputStream finTemp = new FileInputStream(path+TempPramsName);  
		                 if (finTemp!=null) 
		                 {
		                	 bufferTemp = new byte[finTemp.available()];  
		                	 finTemp.read(bufferTemp);  
		                	 finTemp.close();  
						}
		             }  
		             catch (Exception e) 
		        	 {  
		                 e.printStackTrace();  
		             }
		        }
		        else 
		        {
		        	Log.e(TAG, "未找到曲线插值文件"+TempPramsName+",将启用默认配置");
					ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), "未找到曲线插值文件"+TempPramsName+",将启用默认配置");

		        	InputStream inputStreamTemp = null ;
		    		inputStreamTemp= AICApplication.getApplication().getResources().openRawResource(R.raw.tempurature);
		    		bufferTemp = null;
		    		try 
		    		{
		    			bufferTemp = new byte[inputStreamTemp.available()];
		    		} catch (IOException e) 
		    		{
		    			// TODO Auto-generated catch block
		    			e.printStackTrace();
		    		}
		    		try 
		    		{
		    			inputStreamTemp.read(bufferTemp);
		    		} catch (IOException e)
		    		{
		    			// TODO Auto-generated catch block
		    			e.printStackTrace();
		    		}
				}
		        int TempFileLength = bufferTemp.length;
				if (TempFileLength > 0) {

					byte pData[] = new byte[TempFileLength];
					System.arraycopy(bufferTemp, 0, pData, 0, TempFileLength);
					if (!ParseStrToCubicSpline(pData, m_CubicSpline)) {
//						Toast.makeText(null, "曲线插值文件数据格式有误", Toast.LENGTH_LONG).show();
						Log.e(TAG, "曲线插值文件数据格式有误");
						ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), "曲线插值文件数据格式有误");
					}
					else 
					{

					}
				}
				else
				{
//					Toast.makeText(null, "文件长度不能为空。", Toast.LENGTH_LONG).show();
					Log.e(TAG, "文件长度不能为空。");
					ToastUtil.showToast(AICApplication.getApplication().getApplicationContext(), "曲线插值文件长度不能为空");
				}
			}
		}
	
	 public void getNormalPramsFromRaw()
	    {
	    	
	    	InputStream inputStreamNormalPrams = null;
			inputStreamNormalPrams = AICApplication.getApplication().getResources().openRawResource(R.raw.vibrate);
			byte[] bufferNormalPrams = null;
			try {
				bufferNormalPrams = new byte[inputStreamNormalPrams.available()];
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				inputStreamNormalPrams.read(bufferNormalPrams);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			int FileLengthNormal = bufferNormalPrams.length;
			if (FileLengthNormal > 0) {
				String strMormalPrams = new String(bufferNormalPrams);
				String[] mormalPrams = strMormalPrams.split("\\*");
				String[] shuju = new String[mormalPrams.length];
				for (int i = 0; i < mormalPrams.length; i++) {
					int start = mormalPrams[i].indexOf(":");
					int end = mormalPrams[i].length();
					shuju[i] = mormalPrams[i].substring(start + 1, end);
				}
				try {
					mDefaultT = Float.parseFloat(shuju[0].toString());
					mDefaultA = Float.parseFloat(shuju[1].toString());
					mDefaultV = Float.parseFloat(shuju[2].toString());
					mDefaultD = Float.parseFloat(shuju[3].toString());
				} catch (Exception e) {
					// TODO: handle exception
//					Toast.makeText(null, "默认文件res/raw/vibrate校准数据格式有误", 0).show();
					Log.e(TAG, "默认文件res/raw/vibrate校准数据格式有误");
				}
			}
	    }
	 /**
	 * @param filename
	 * 获取选中传感器的温度曲线内容
	 */
	public static String getTemperatureCurve(String filename) 
	{
		String curve="";
		// 获得存储卡的路径
		Setting setting = new Setting();
		String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
		File fNormalPrams = new File(path + filename);
		byte[] bufferNormalPrams = null;
		if (fNormalPrams.exists()) 
		{
			try 
			{
				FileInputStream finNormalPrams = new FileInputStream(path+ filename);
				if (finNormalPrams != null) 
				{
					bufferNormalPrams = new byte[finNormalPrams.available()];
					finNormalPrams.read(bufferNormalPrams);
					finNormalPrams.close();
				}
			} 
			catch (Exception e) 
			{
				Log.e("test", "读取本地文件出现异常:" + e.getMessage());
				return curve;
			}
			int FileLengthNormal = bufferNormalPrams.length;
			if (FileLengthNormal > 0) 
			{
				curve = new String(bufferNormalPrams);
//				UpdateChart(strMormalPrams);
			}
		} 
		else 
		{
			curve = getDefaultTempCurveFromRaw();
//			UpdateChart(strCurve);
		}
		return curve;
	}
	/**
	 * @param result
	 * @return 根据传入的温度校准曲线值获取当前曲线包含的校正点个数
	 */
	public static int getCurveTotalPoints(String result)
	{
		int length=0;
		 try
         {
			 length= (result.length() / 16) / 2;
         }
		 catch (Exception ex)
         {
        	 Log.e("ReceivedDataAnalysis", ex.getMessage());
         }
		 return length;
		 
	}
	/**
	 * @return 根据传入的需要校正的温度点索引，获取需要校准的温度值
	 */
	public static int getShouldCalPointsValue(int point)
	{
		int value=0;
		int temp_lower_limit = CommonDef.TempuratureCalibrationLowerLimit;
		int temp_upper_limit = CommonDef.TempuratureCalibrationUpperLimit;
		int temp_step = CommonDef.TempuratureCalibrationStepValue;
		value=temp_lower_limit+temp_step*point;
		return value;
	}
	/**
	 * @return 获取温度校准范围
	 */
	public static String getTempCalRange()
	{
		return String.valueOf(CommonDef.TempuratureCalibrationLowerLimit)+"~"+String.valueOf(CommonDef.TempuratureCalibrationUpperLimit);
	}
	/**
	 * @return 获取温度校准步进值
	 */
	public static String getTempCalStep()
	{
		return String.valueOf(CommonDef.TempuratureCalibrationStepValue);
	}
	/**
	 * @return 根据默认校准上下限及步进值获取传感器校准点数
	 */
	public static int getCalibrationTotalPoints()
	{
		int totalpoints=0;//曲线总的校准点数
		int lowerlimit=CommonDef.TempuratureCalibrationLowerLimit;
		int upperlimit=CommonDef.TempuratureCalibrationUpperLimit;
		int stepvalue=CommonDef.TempuratureCalibrationStepValue;
		totalpoints=(upperlimit-lowerlimit)/stepvalue+1;
		return totalpoints;
	}
	public static void UpdateCurve(Context context,String result,double xvalue,double yvalue,int pointindex,String blemac) 
	{
		//1、获取新的校准数据，并写入校准曲线文件
		//2、校准文件写入成功之后，更新校准记录
		try 
		{
			Setting setting =new Setting();
			String filename=blemac+"-temp.txt";//校准完毕的点写入的校准文件名称
			String path=setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting)+filename;//校准完毕的点写入的校准文件位置
			
			int length = (result.length() / 16) / 2;
			double[] xArray = new double[length];
			double[] yArray = new double[length];
			float[] xcopyArray = new float[length];
			float[] ycopyArray = new float[length];
			String newcurve = "";
			for (int i = 0; i < length; i++) 
			{
				xArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(result.substring(i * 16, i * 16 + 16)));
				yArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(result.substring((length + i) * 16, (length + i) * 16 + 16)));
				xcopyArray[i]=(float)xArray[i];
				ycopyArray[i]=(float)yArray[i];
			}
//			if (getCalibrationTotalPoints()!=length) 
//			{
//				//校准的基准曲线上的基准点数与校准标准点数不一致
//			}
//			else
			{
				int factpointindex=pointindex+1;//实际曲线是从-50，-20，-10~320，但是标定的时候-50永远不标定，所以实际标定的点实在实际曲线对应的索引向后一位
				xArray[factpointindex] = xvalue;
				yArray[factpointindex] = yvalue;
				xcopyArray[factpointindex]=(float)xArray[factpointindex];
				ycopyArray[factpointindex]=(float)xArray[factpointindex];
			}
			
			for (int i = 0; i < length; i++) 
			{
				newcurve += ArrayUtil.bytes2hex03(ArrayUtil.doubleToBytes(xArray[i]));
			}
			for (int i = 0; i < length; i++) 
			{
				newcurve += ArrayUtil.bytes2hex03(ArrayUtil.doubleToBytes(yArray[i]));
			}
			
			try 
			{
				SystemUtil.writeFileToSD(path, newcurve);
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				ToastUtil.showToast(context, "将校准完的传感器曲线写入本地时出现异常:"+ e.getMessage());
				Log.e("ReceiveDataAnalysis","将校准完的传感器曲线写入本地时出现异常:"+ e.getMessage());
				LogUtil.GetInstance().append("将校准完的传感器曲线写入本地时出现异常:"+ e.getMessage());
				return;
			}
			CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Calibration_Chart, new CurveValuePair(xcopyArray,ycopyArray));
			
			String key_sensor="";
			String calibrationrecord="";
			boolean isCurBLERecordExist=false;//当前校准的传感器，是否在校准记录里已经有了记录了，=false,无记录；=true,有记录；
			String path_record = setting.get_CalibrationRecordFile();//校准记录存储文件路径及名称
			calibrationrecord = SystemUtil.openFile(path_record);//校准记录的内容
			if (!StringUtil.isNullOrWhiteSpace(calibrationrecord)) //存在校准记录且内容不为空
			{
				String[] record = calibrationrecord.split("]");
				String[] record_2 = new String[record.length];
				for (int i = 0; i < record.length; i++)
				{
					record_2[i] = record[i].substring(record[i].indexOf("[") + 1);
					key_sensor = record_2[i].split(",")[0];
					if (blemac.equals(key_sensor)) //当前校准的传感器在校准记录中已经存在，需要覆盖原先的记录
					{
						pointindex++;
						record_2[i]=blemac+","+pointindex;
						isCurBLERecordExist=true;
					}
				}
				calibrationrecord="";
				for (int i = 0; i < record_2.length; i++)
				{
					calibrationrecord+=("["+record_2[i]+"]");
				}
				if (!isCurBLERecordExist) //校准记录中不存在当前校准的传感器记录，在原记录基础上追加新记录
				{
					pointindex++;
					calibrationrecord+=("["+blemac+","+pointindex+"]");
					isCurBLERecordExist=false;
				}
			} 
			else //不存在校准记录或校准记录的内容为空
			{
				pointindex++;
				calibrationrecord="["+blemac+","+pointindex+"]";
			}
			
			try//将新的校准记录写入本地文件
			{
				SystemUtil.writeFileToSD(path_record,calibrationrecord);
				CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index,pointindex);
			}
			catch (IOException e) 
			{
			// TODO Auto-generated catch block
				Log.e("ReceiveDataAnalysis", "当前传感器校准记录写入本地AICCalibrationRecord.txt时出现异常:"+e.getMessage());
				LogUtil.GetInstance().append("当前传感器校准记录写入本地AICCalibrationRecord.txt时出现异常:"+e.getMessage());
			}
		} 
		catch (Exception e) 
		{
			Log.e("UpdateCurve", e.getMessage());
			LogUtil.GetInstance().append("UpdateCurve时出现异常:"+e.getMessage());
		}
	}
	public static boolean getCalibrationCurvePiontsValue(String curve)
	{
		boolean flag=false;
		try 
		{
			DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
			int length = (curve.length() / 16) / 2;
			double[] xArray = new double[length];
			double[] yArray = new double[length];
			float[] xcopyArray = new float[length];
			float[] ycopyArray = new float[length];
			
			for (int i = 0; i < length; i++) 
			{
				xArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring(i * 16, i * 16 + 16)));
				yArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring((length + i) * 16, (length + i) * 16 + 16)));
				xcopyArray[i]=(float)xArray[i];
				ycopyArray[i]=(float)yArray[i];
			}
			flag=true;
			CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Calibration_Chart, new CurveValuePair(xcopyArray,ycopyArray));
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.e("getCalibrationCurvePiontsValue", "读取温度曲线点用于绘制曲线时，出现异常:"+e.getMessage());
			LogUtil.GetInstance().append("读取温度曲线点用于绘制曲线时，出现异常:"+e.getMessage());
			return false;
		}
		return flag;
	}
	public static void judgeCalibrationCurve(Handler _handler,String curve) 
	{
		String xString = "";
		try 
		{
			DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
			int length = (curve.length() / 16) / 2;
			double[] xArray = new double[length];
			double[] yArray = new double[length];
			
			for (int i = 0; i < length; i++) 
			{
				xArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring(i * 16, i * 16 + 16)));
				yArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring((length + i) * 16, (length + i) * 16 + 16)));
			}
			for (int i = 0; i < length - 2; i++) 
			{
				double xielv1 = (yArray[i + 1] - yArray[i])/ (xArray[i + 1] - xArray[i]);
				double xielv2 = (yArray[i + 2] - yArray[i + 1])/ (xArray[i + 2] - xArray[i + 1]);
				if (xielv1 < xielv2) {
					xString += "校准温度:" + Double.parseDouble(df.format(yArray[i])) + "℃、" +Double.parseDouble(df.format(yArray[i+1]))+ "℃、" + Double.parseDouble(df.format(yArray[i+2])) + "℃" + "曲线变化较大;\n";
				}
				if (xielv1 < 0) {
					xString += "校准温度:" + Double.parseDouble(df.format(yArray[i])) + "℃、" + Double.parseDouble(df.format(yArray[i+1]))+ "℃"+ "曲线走向异常;\n";
				}
				if (xielv2 < 0) {
					xString += "校准温度:" + Double.parseDouble(df.format(yArray[i+1])) + "℃、" + Double.parseDouble(df.format(yArray[i+2]))+ "℃" + "曲线走向异常;\n";
				}
			}
		} 
		catch (Exception e) 
		{
			// TODO: handle exception
			xString="转换温度曲线值并进行比较时出现异常:" + e.getMessage();
		}
		_handler.obtainMessage(Constants.HANDLER_CHECK_CALIBRATION_CURVE, 0, 0, xString).sendToTarget();
	}
//	public static boolean judgeCalibrationCurve(Handler handler,String filename,double xvalue,double yvalue) 
//	{
//		boolean flag=false;
//		try 
//		{
//			String curve="";
//			// 获得存储卡的路径
//			Setting setting = new Setting();
//			String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
//			File fNormalPrams = new File(path + filename);
//			byte[] bufferNormalPrams = null;
//			if (fNormalPrams.exists()) 
//			{
//				try 
//				{
//					FileInputStream finNormalPrams = new FileInputStream(path+ filename);
//					if (finNormalPrams != null) 
//					{
//						bufferNormalPrams = new byte[finNormalPrams.available()];
//						finNormalPrams.read(bufferNormalPrams);
//						finNormalPrams.close();
//					}
//				} 
//				catch (Exception e) 
//				{
//					Log.e("test", "读取温度曲线出现异常:" + e.getMessage());
//					handler.obtainMessage(Constants.HANDLER_READ_CALIBRATION_CURVE, 0, 0, "读取温度曲线出现异常:" + e.getMessage());
//					return false;
//				}
//				int FileLengthNormal = bufferNormalPrams.length;
//				if (FileLengthNormal > 0) 
//				{
//					curve = new String(bufferNormalPrams);
//					handler.obtainMessage(Constants.HANDLER_READ_CALIBRATION_CURVE, 1, 0, "读取"+filename+"温度曲线成功");
//				}
//			} 
//			else 
//			{
//				curve = getDefaultTempCurveFromRaw();
//				handler.obtainMessage(Constants.HANDLER_READ_CALIBRATION_CURVE, 1, 0, "未找到"+filename+"温度曲线，调用默认温度曲线");
//			}
//
//			try {
//				int length = (curve.length() / 16) / 2;
//				double[] xArray = new double[length];
//				double[] yArray = new double[length];
//				String xString = "";
//				for (int i = 0; i < length; i++) 
//				{
//					xArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring(i * 16, i * 16 + 16)));
//					yArray[i] = ArrayUtil.bytes2Double(ArrayUtil.toByteArray(curve.substring((length + i) * 16, (length + i) * 16 + 16)));
//				}
//				for (int i = 0; i < length-2; i++) 
//				{
//					double xielv1=(yArray[i+1]-yArray[i])/(xArray[i+1]-xArray[i]);
//					double xielv2=(yArray[i+2]-yArray[i+1])/(xArray[i+2]-xArray[i+1]);
//					if (xielv1<xielv2) 
//					{
//						Log.e("judgeCalibrationCurve", xArray[i]+","+yArray[i]+";"+xArray[i+1]+","+yArray[i+1]+";"+xArray[i+2]+","+yArray[i+2]+";");
//						xString+="校准温度:"+yArray[i]+"℃、"+yArray[i+1]+"℃、"+yArray[i+2]+"℃"+"曲线变化较大;\n";
//					}
//					if (xielv1<0) {
//						Log.e("judgeCalibrationCurve", xArray[i]+","+yArray[i]+";"+xArray[i+1]+","+yArray[i+1]+";");
//						xString+="校准温度:"+yArray[i]+"℃、"+yArray[i+1]+"℃"+"曲线走向异常;\n";
//					}
//					if (xielv2<0) {
//						Log.e("judgeCalibrationCurve", xArray[i]+","+yArray[i]+";"+xArray[i+1]+","+yArray[i+1]+";");
//						xString+="校准温度:"+yArray[i+1]+"℃、"+yArray[i+2]+"℃"+"曲线走向异常;\n";
//					}
//				}
//				flag=true;
//			} catch (Exception e) {
//				// TODO: handle exception
//				handler.obtainMessage(Constants.HANDLER_READ_CALIBRATION_CURVE, 0, 0, "转换温度曲线值并进行比较时出现异常:"+e.getMessage());
//				return false;
//			}
//			
//		} 
//		catch (Exception e) 
//		{
//			handler.obtainMessage(Constants.HANDLER_READ_CALIBRATION_CURVE, 0, 0, "判断温度曲线值时出现异常:"+e.getMessage());
//			return false;
//		}
//		return flag;
//	}
	public static String getDefaultTempCurveFromRaw()
	{
		String strCurve="";
		InputStream inputStreamTempCurve = null;
		inputStreamTempCurve = AICApplication.getApplication().getResources().openRawResource(R.raw.tempurature);
		byte[] bufferTempCurve = null;
		try {
			bufferTempCurve = new byte[inputStreamTempCurve.available()];
			inputStreamTempCurve.read(bufferTempCurve);
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			Log.e("ReceiveDataAnalysis", "获取温度默认校准曲线数据时出现异常："+e.getMessage());
			LogUtil.GetInstance().append("获取温度默认校准曲线数据时出现异常："+e.getMessage());
			return strCurve;
		}

		int FileLength = bufferTempCurve.length;
		if (FileLength > 0) {
			strCurve = new String(bufferTempCurve);
		}
		return strCurve;
	}
    public double getDouble(byte[] bytes)//2016-03-24 liuhg添加
    {
        long l = getLong(bytes);
        System.out.println(l);
        return Double.longBitsToDouble(l);
    }
	
	public long getLong(byte[] bytes)//2016-03-24 liuhg添加
    {
        return(0xffL & (long)bytes[0]) | (0xff00L & ((long)bytes[1] << 8)) | (0xff0000L & ((long)bytes[2] << 16)) | (0xff000000L & ((long)bytes[3] << 24))
         | (0xff00000000L & ((long)bytes[4] << 32)) | (0xff0000000000L & ((long)bytes[5] << 40)) | (0xff000000000000L & ((long)bytes[6] << 48)) | (0xff00000000000000L & ((long)bytes[7] << 56));
    }
	
	public byte[] hexStringToByte(String hex) {//2016-03-24 liuhg添加
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}

	private byte toByte(char c) {//2016-03-24 liuhg添加
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	} 
	
	
	public boolean ParseStrToCubicSpline(final byte pStrData[],CubicSpline p_CubicSplineFabsLimitAlarmCurve)//2016-03-24 liuhg添加
	{
//		final int MAXCORN = 2048;//2016-05-24 liuhg修改前原程序
		final int MAXCORN = pStrData.length;//2016-05-24 liuhg修改
		int LenCor = 0;
		boolean nRe = true;
		int xLen = 0;
		double pxFabsLimitAlarmCurve[] = null;
		double[] pxTenpFabsLimitAlarmCurve = null;
		int NLENDOUBLE;
		int DoubleStr;
		NLENDOUBLE = 8;
		DoubleStr = NLENDOUBLE << 1;

		if (pStrData != null) {
			int CorN = pStrData.length;
			if (CorN > MAXCORN)
				return false;

			if (CorN % DoubleStr != 0 || CorN < DoubleStr)// 必须是double长度的倍数。
				return false;

			LenCor = CorN / DoubleStr;

			xLen = (int) (LenCor / 2);
			if (!p_CubicSplineFabsLimitAlarmCurve.malloc(xLen))
				return false;

			pxFabsLimitAlarmCurve = new double[LenCor];

			pxTenpFabsLimitAlarmCurve = pxFabsLimitAlarmCurve;

			byte[] pxTFabs = null;
			int ii;
			byte tpx[] = new byte[8];
			String string = new String(pStrData);
			pxTFabs = hexStringToByte(string);

			for (ii = 0; ii < LenCor; ii++) {
				tpx[0] = pxTFabs[ii * NLENDOUBLE + 0];
				tpx[1] = pxTFabs[ii * NLENDOUBLE + 1];
				tpx[2] = pxTFabs[ii * NLENDOUBLE + 2];
				tpx[3] = pxTFabs[ii * NLENDOUBLE + 3];
				tpx[4] = pxTFabs[ii * NLENDOUBLE + 4];
				tpx[5] = pxTFabs[ii * NLENDOUBLE + 5];
				tpx[6] = pxTFabs[ii * NLENDOUBLE + 6];
				tpx[7] = pxTFabs[ii * NLENDOUBLE + 7];

				pxTenpFabsLimitAlarmCurve[ii] = getDouble(tpx);

			}
		}
		double xshuzu[] = new double[pxTenpFabsLimitAlarmCurve.length / 2];
		double yshuzu[] = new double[pxTenpFabsLimitAlarmCurve.length / 2];
		System.arraycopy(pxTenpFabsLimitAlarmCurve, 0, xshuzu, 0,
				pxTenpFabsLimitAlarmCurve.length / 2);
		System.arraycopy(pxTenpFabsLimitAlarmCurve,
				pxTenpFabsLimitAlarmCurve.length / 2, yshuzu, 0,
				pxTenpFabsLimitAlarmCurve.length / 2);
		p_CubicSplineFabsLimitAlarmCurve.InterpolateNatural(xshuzu, xLen,
				yshuzu, xLen);

		return nRe;

	}
	public static boolean saveSensorPrams(String _bluetoothAddress,float defaulta, float defaultv, float defaultd, float defaultt) {
		boolean flag=false;
		try 
		{
			Setting setting = new Setting();// 2016-04-13 liuhg添加
			String temp = "Tempurature:" + String.valueOf(defaultt) + "*\r\n";
			String X_A = "X-A:" + String.valueOf(defaulta) + "*\r\n";
			String X_V = "X-V:" + String.valueOf(defaultv) + "*\r\n";
			String X_D = "X-D:" + String.valueOf(defaultd) + "*\r\n";
			String contentString = temp + X_A + X_V + X_D;
			String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
			String fileName = _bluetoothAddress.replace(":","") + "-vibrate.txt";
			SystemUtil.writeFileToSD(path+fileName, contentString);
//			writeToFile(contentString, path, fileName);
			flag=true;
		} 
		catch (Exception e) {
			AICService.addLog("保存传感器参数saveSensorPrams时出现异常:"+e.getMessage());
			return false;
		}
		return flag;
	}

	/**
	 * @author liuhg
	 */
//	public void writeToFile(String content, String path, String fileName) {// 2016-04-13
//																			// liuhg添加
//		File file = new File(path + fileName);
//		file.mkdirs();
//		try {
//			if (file.exists()) {
//				file.delete();
//			}
//			file.createNewFile();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		try {
//			OutputStream outstream = new FileOutputStream(file);
//			OutputStreamWriter out = new OutputStreamWriter(outstream);
//			out.write(content);
//			out.close();
//		} catch (java.io.IOException e) {
//			e.printStackTrace();
//		}
//	}
	public static float getmEmissivity(float emissivity) 
	{
		return (float) Math.sqrt(Math.sqrt(emissivity));
	}
}
